/**
 * @Author: liangshuchang
 * @Description:  货主端运单列表
 */

import React from 'react';
import {
  View,
  StyleSheet,
  Image,
  NativeModules,
  SafeAreaView,
  TouchableOpacity,
  InteractionManager,
} from 'react-native';
import { iconWayOrderCoffee, iconWayOrderGray } from '../../../../image';
import { BackImage, msg, Header, Button } from '../../../../common';
import {
  px2dp,
  isAndroid,
  mainBgColorLightGray
} from '../../../../common/styles';
import HeadTabs from '../../../../components/HeadTabs';
import XmList from '../../../../components/XmList';
import supply from '../../../../api/supply';
import tool from '../../../../common/utils/getDate';
import OrderInfoCard from './components/order-info-card';

export default class Source extends React.Component {
  static navigationOptions = () => ({
    title: '订单',
    tabBarIcon: ({ focused }) => (
      <Image
        source={focused ? iconWayOrderCoffee : iconWayOrderGray}
        style={{ width: 24, height: 24 }}
      />
    ),
  });

  constructor(props) {
    super(props);
    this.state = ({
      state: -1,
      orderList: [],
      pageNo: 1,
      pageSize: 3,
      hasMorePage: true,
      isLoading: false,
      showFoot: 1, // 控制foot， 0：隐藏footer  1：已加载完成,没有更多数据   2 ：显示加载中
      unitList: []
    });
  }

  componentDidMount() {
    const { navigation } = this.props;
    const state = navigation.state || {};
    const params = state.params || {};
    const { routerFrom, orderNo } = params;
    this.loadData();
    this.unitList();
    // this.listener = DeviceEventEmitter.addListener('UPDATE_DETAIL', (itemsShow) => {
    //   this.setState({
    //     routerFrom,
    //     pageNo: 1,
    //     orderList: []
    //   }, () => {
    //     InteractionManager.runAfterInteractions(() => {
    //       this.loadData();
    //     })
    //   });
    // });
    // InteractionManager.runAfterInteractions(() => {
    //   this.loadData();
    // })
  }

  tabSources = [
    // 0.待调度 1.完成调度 2.已取消 3.已过期
    { tab: '全部', type: -1 },
    { tab: '待调度', type: 0 },
    { tab: '已完成', type: 1 },
  ];

  render() {
    // 0.待调度 1.完成调度 2.已取消 3.已过期
    const { state, orderList, isLoading, hasMorePage, showFoot } = this.state;
    return (
      <SafeAreaView style={styles.container}>
        <Header
          title='我的订单'
          renderLeft={this._renderLeft}
        />
        <HeadTabs
          tabSources={this.tabSources}
          changeStatus={(type) => this.changeStatus(type)}
          status={state}
        />
        <XmList
          sources={orderList}
          renderItem={this._renderItem}
          style={styles.xmListContainer}
          isLoading={isLoading}
          onDropdownRefresh={this.loadData}
          hasMorePage={hasMorePage}
          onPullUpMore={this.LoadMore}
          singleKey={item => item.id}
          showFoot={showFoot}
        />
      </SafeAreaView>
    );
  }

  _renderLeft = () => {
    return (
      <TouchableOpacity
        activeOpacity={0.8}
        style={isAndroid ? { paddingVertical: px2dp(14), paddingHorizontal: px2dp(40) } :
          { paddingVertical: px2dp(14), paddingRight: px2dp(40) }}
        onPress={() => {
          msg.emit('router: back');
        }}
      >
        <BackImage />
      </TouchableOpacity>
    );
  }

  _renderItem = ({ item }) => {
    const { unitList } = this.state;
    return (
      <TouchableOpacity
        activeOpacity={0.7}
        onPress={() => {
          msg.emit('router: goToNext', {
            routeName: 'WaybillList',
            orderId: item.orderId,
            orderNo: item.orderNo,
          });
        }}
      >
        <OrderInfoCard
          unitList={unitList}
          item={item}
          cancelHandle={orderId => this._cancelHandle(orderId)}
        />
      </TouchableOpacity>
    );
  };

  // tab点击切换
  changeStatus = (state) => {
    this.setState({
      state,
    }, () => {
      InteractionManager.runAfterInteractions(() => {
        this.loadData();
      });
    });
  }

  // 下拉刷新
  loadData = () => {
    this.setState({
      isLoading: true,
      pageNo: 1,
      orderList: [],
      showFoot: 0
    }, () => {
      this.contractOrderPage('dropdown');
    });
  }

  // 上拉加载更多
  LoadMore = () => {
    this.setState({ showFoot: 2 }, () => this.contractOrderPage('pullMore'));
  }

  // 取消
  _cancelHandle = (orderId) => {
    const parameter = { content: '确定要取消订单吗？', leftStr: '不了' };
    NativeModules.WindowModule.showWindow(parameter, e => {
      e === 1 && InteractionManager.runAfterInteractions(() => {
        supply.cancelOrder(orderId).then(res => {
          if (res.success) {
            this.loadData();
          } else {
            msg.emit('app:tip', { text: res.msg });
          }
        });
      });
    });
  }

  /**
   * 接口调用
   * @param type
   */

  contractOrderPage = (type) => {
    const { orderList, pageNo, pageSize, state } = this.state;
    let newOrderList = [];
    supply.contractOrderPage({
      pageNo,
      pageSize,
      status: state === -1 ? '' : state,
    }).then(res => {
      if (res.success) {
        const { records, pages } = res.data;
        if (type === 'dropdown') {
          this.setState({ orderList: records });
        }
        if (type === 'pullMore') {
          if (pageNo > pages) {
            this.setState({ showFoot: 1 });
            return;
          }
          newOrderList = [...orderList, ...records];
          this.setState({ orderList: newOrderList });
        }
        this.setState({ isLoading: false, pageNo: pageNo + 1 });
      } else {
        msg.emit('app:tip', { text: res.msg });
      }
    });
  }

  unitList = () => {
    supply.unitList().then(res => {
      if (res.success) {
        this.setState({ unitList: res.data });
      }
    });
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  xmListContainer: {
    flex: 1,
    backgroundColor: mainBgColorLightGray,
    padding: px2dp(24),
  },
});
